package com.agricultural.machine.decorator;

import com.agricultural.machine.common.IMachine;
import java.util.HashMap;
import java.util.Map;

/**
 * 性能监控装饰器类 - 装饰器模式
 */
public class PerformanceMonitorDecorator extends MachineDecorator {
    private final Map<String, Long> operationTimes;
    private final Map<String, Integer> operationCounts;
    
    public PerformanceMonitorDecorator(IMachine decoratedMachine) {
        super(decoratedMachine);
        this.operationTimes = new HashMap<>();
        this.operationCounts = new HashMap<>();
    }
    
    @Override
    public void start() {
        long startTime = System.currentTimeMillis();
        super.start();
        recordOperationTime("start", System.currentTimeMillis() - startTime);
    }
    
    @Override
    public void stop() {
        long startTime = System.currentTimeMillis();
        super.stop();
        recordOperationTime("stop", System.currentTimeMillis() - startTime);
    }
    
    @Override
    public void executeTask(String task) {
        long startTime = System.currentTimeMillis();
        super.executeTask(task);
        recordOperationTime("executeTask", System.currentTimeMillis() - startTime);
    }
    
    @Override
    public void updatePosition(double x, double y) {
        long startTime = System.currentTimeMillis();
        super.updatePosition(x, y);
        recordOperationTime("updatePosition", System.currentTimeMillis() - startTime);
    }
    
    @Override
    public void work() {
        long startTime = System.currentTimeMillis();
        super.work();
        recordOperationTime("work", System.currentTimeMillis() - startTime);
    }
    
    /**
     * 记录操作时间
     */
    private void recordOperationTime(String operation, long time) {
        // 更新总时间
        operationTimes.put(operation, operationTimes.getOrDefault(operation, 0L) + time);
        
        // 更新计数
        operationCounts.put(operation, operationCounts.getOrDefault(operation, 0) + 1);
        
        // 输出性能信息
        System.out.println("性能监控 - 农机(ID=" + getMachineId() + ") " + operation + 
                          " 操作耗时: " + time + "ms, 平均耗时: " + 
                          (operationTimes.get(operation) / operationCounts.get(operation)) + "ms");
    }
    
    /**
     * 获取性能报告
     */
    public Map<String, Double> getPerformanceReport() {
        Map<String, Double> report = new HashMap<>();
        
        for (String operation : operationTimes.keySet()) {
            long totalTime = operationTimes.get(operation);
            int count = operationCounts.get(operation);
            double avgTime = (double) totalTime / count;
            report.put(operation, avgTime);
        }
        
        return report;
    }
}




























